package com.ashin.byteto;

import org.junit.Test;

/**
 * 字节数据转16进制字符串
 * <p>
 * https://blog.csdn.net/hll174/article/details/51063689
 * 
 * @author Ashin
 *
 */
public class ByteToHex {

    private byte[] bytes = "hello byte!".getBytes();

    /**
     * 字节码转换成16进制字符串
     * 
     * @param b
     * @return String
     */
    @Test
    public void byte2hex1() {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < bytes.length; n++) {
            stmp = (Integer.toHexString(bytes[n] & 0XFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
            if (n < bytes.length - 1) {
                hs = hs + "";
            }
        }
        System.out.println(hs.toLowerCase());
    }

    @Test
    public void byte2Hex() {
        StringBuilder hexString = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String shaHex = Integer.toHexString(bytes[i] & 0xFF);
            if (shaHex.length() < 2) {
                hexString.append(0);
            }
            hexString.append(shaHex);
        }

        System.out.println(hexString.toString().toLowerCase());
    }
}
